import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class ThreadDemo1 {
    public static void main(String[] args) throws InterruptedException {
        //这里的10代表10个任务
        CountDownLatch latch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            int n = i;
            Thread t = new Thread(() -> {
                Random random = new Random();
                System.out.println("线程" + n + "开始下载");
                try {
                    Thread.sleep((random.nextInt(5) +1) * 1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("线程" + n + "下载完毕");
                //每个任务执行完毕就countDown一次，用来记录这个任务执行完了
                latch.countDown();
            });
            t.start();
        }
        //等待所有任务都执行完毕
        latch.await();
        System.out.println("所有任务下载完毕");
    }
}
